<template>
    <div class="order-detail" v-loading="loading">
        <order-banner @processClick="processClick" :detail="repairDetail" />
        <template v-if="store.stateOperation !== 5">
            <div class="order-item" v-if="store.stateOperation !== 1">
                <div class="item" v-for="(item, index) in repairDetail?.repairDetails" @click="itemClick(index, item)" :class="{ 'item-active': itemIndex === index }">
                    <span class="hot" />
                    <span>{{ item.structureName }}</span>
                </div>
            </div>
            <div class="order-main">
                <div class="left" v-if="store.stateOperation === 1">
                    <orderTree @handlerNode="handlerNode" @typeClick="typeClick" ref="orderTreeRef" />
                </div>
                <div class="right">
                    <association-policy
                        :tableConfig="store.stateOperation === 1 ? tableConfig : examinetableConfig"
                        :isShowTitle="store.stateOperation === 1"
                        titleText="关联策略"
                        ref="associationPolicyRef"
                    />
                    <fault
                        :isSet="store.stateOperation === 1"
                        titleText="故障现象"
                        :remark="detail?.remark"
                        :imgList="detail?.images || store.treeSelectNode.imgList || []"
                        @handlerInput="handlerInput"
                        @upload="upload"
                        placeholder="请输入故障描述"
                    />
                </div>
            </div>
            <div class="feedback" v-if="repairDetail.status == 7 || repairDetail.status == 6 || repairDetail.status == 5 || store.stateOperation == 4">
                <association-policy
                    :tableConfig="store.stateOperation === 4 ? feedbacktableConfig : feedbackLooktableConfig"
                    titleText="处理反馈"
                    ref="feedbackRef"
                    :userName="repairDetail?.repairDetails && repairDetail.repairDetails[0]?.disposeOperaterName"
                />
                <fault
                    titleText="处理结果"
                    :isSet="store.stateOperation !== 6 && store.stateOperation !== 3"
                    :remark="detail?.disposeRemark"
                    :imgList="detail?.disposeImages || []"
                    @handlerInput="handlerInput"
                    @upload="upload"
                    placeholder="请输入处理描述"
                />
            </div>
            <div class="examine" v-if="repairDetail.status == 2">
                <div class="examine-top">
                    <span>审核结果</span>
                    <span>审核人：{{ repairDetail.checkOperaterName }}</span>
                </div>
                <div class="examine-article">{{ repairDetail.remark }}</div>
            </div>
            <div class="examine" v-if="repairDetail.status == 7 || repairDetail.status == 6">
                <div class="examine-top">
                    <span>验收反馈</span>
                    <span>验收人：{{ repairDetail.checkOperaterName }}</span>
                </div>
                <div class="examine-article">{{ repairDetail.status == 2 || repairDetail.status == 7 ? repairDetail.remark : "已通过" }}</div>
            </div>
        </template>
        <template v-else>
            <distribution :peopleTree="peopleTree" :responsible="responsible" ref="distributionRef" />
        </template>
        <div class="btns" v-if="store.stateOperation !== 3">
            <el-button type="primary" class="confrim" @click="leftBtnClick">{{ btnText.left }}</el-button>
            <w-button :isShowIcon="false" @click="rightBtnClick">{{ btnText.right }}</w-button>
        </div>
        <w-popup :isShowPopup="isShowExaminePopup" @close="popupClose(popFormData)" @confrim="popupConfrim(examineType)" :title="examineTitle">
            <w-form :formConfig="formConfig" :formData="popFormData" :rules="rules" ref="wFormRef"></w-form>
            <template #top v-if="examineType === 0">
                <div class="notice-one">确认故障，提交“维修流程”</div>
            </template>
        </w-popup>
        <w-popup :isShowPopup="isShowProcessPopup" @close="isShowProcessPopup = false" @confrim="isShowProcessPopup = false" width="800" :isShowCancel="false" class="process" confrimText="确定">
            <order-process :detail="repairDetail"></order-process>
        </w-popup>
    </div>
</template>

<script setup>
import orderBanner from "./cpn/orderBanner.vue";
import wButton from "@/components/wButton.vue";
import orderProcess from "./cpn/orderProcess.vue";
import associationPolicy from "./cpn/associationPolicy.vue";
import fault from "./cpn/fault.vue";
import distribution from "./cpn/distribution.vue";
import orderTree from "./cpn/orderTree.vue";

import { mainStore } from "@/store/main.js";
import { useReportOrderDetail } from "@/store/reportOrderDetail.js";
import { getStructureTreeList, saveRepair, getRepair, getReportDist, checkRepair, setAssign, setHandler, acceptRepair } from "@/service/api/report.js";
import { getDpt } from "@/service/api/maintenance.js";
import { examineConfrimConfig, examineRejectConfig, tableConfig, examinetableConfig, feedbacktableConfig, feedbackLooktableConfig, examineConfrimRules, rejectRules } from "./config.js";
import { ref, nextTick, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { cloneDeep } from "@/utils/utils.js";
import { BASE_URL } from "@/service/request/config";

const router = useRouter();
const route = useRoute();
const mStore = mainStore();
const store = useReportOrderDetail();
const loading = ref(false);
const itemIndex = ref(0);
const wFormRef = ref(null);
const detail = ref({});
const orderTreeRef = ref(null);
const associationPolicyRef = ref(null);
const examineTitle = ref("审核");

const itemClick = (index, data) => {
    itemIndex.value = index;
    associationPolicyRef.value.tableRef.tableData = data.repairFeedbackInfos;
    if (feedbackRef.value) feedbackRef.value.tableRef.tableData = data.repairFeedbackInfos;
    detail.value = data;
};
const handlerInput = (value) => {
    store.stateOperation === 4 ? (detail.value.disposeRemark = value) : (store.treeSelectNode.remark = value);
};
const upload = (imgList) => {
    store.stateOperation === 4 ? (detail.value.disposeImages = imgList) : (store.treeSelectNode.imgList = imgList);
};
const typeClick = (index) => {
    store.getDeviceTree({ id: Number(mStore.tableData.areaNameId), strategyId: mStore.tableData.strategyId, structureType: index }, () => {
        nextTick(() => {
            orderTreeRef.value.treeCpnRef.treeRef.setCurrentKey(store.treeData[0]?.childList[0]?.id);
        });
        handlerNode({ level: 2, data: store.treeData[0]?.childList[0] });
    });
    associationPolicyRef.value.tableRef.tableData = [];
};
function getReapirDetail(id) {
    return new Promise((reslove, reject) => {
        getRepair({ id }).then((res) => {
            repairDetail.value = res.data;
            if (res.code === 200) {
                reslove(res.data);
            }
        });
    });
}
const repairDetail = ref([]);
const formConfig = ref({});
const feedbackRef = ref(null);
let examineType = 0; //0同意 1不同意
const isShowExaminePopup = ref(false);
const popFormData = ref({});
const examinePopFormData = reactive({ department: "", grade: "" });
const rejectPopFormData = reactive({ remark: "" });
let rules = {};
const leftBtnClick = () => {
    switch (store.stateOperation) {
        case 1:
            loading.value = true;
            const repairDetails = [];
            recursionData(store.treeData);
            const repair = {
                soursce: 2,
                grade: mStore.tableData.jobOrderLevel,
                areaLocation: Number(mStore.tableData.areaNameId),
                equipmentId: mStore.tableData.deviceInfoId,
                major: orderTreeRef.value.itemIndex,
                repairDepartment: mStore.userInfo.deptId,
                repairDetails
            };
            function recursionData(arr) {
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i].depth !== "0" && arr[i].hot.length) {
                        repairDetails.push({
                            structureId: arr[i].id,
                            picture: arr[i].imgList.map((item) => item.id).join(","),
                            remark: arr[i].remark,
                            repairDetailStrategies: arr[i].hot
                                .filter((item) => item.check !== "否" || item.check !== "无")
                                .map((item) => ({
                                    inspectionItemName: item.inspectionItemName,
                                    inspectionItemId: item.inspectionItemId,
                                    suggestDisposalMethod: item.handle,
                                    inspectionResult: item.check
                                }))
                        });
                    }
                    if (!arr[i].childList.length) continue;
                    recursionData(arr[i].childList);
                }
            }
            saveRepair(repair)
                .then((res) => {
                    loading.value = false;
                    if (res.code === 200) {
                        ElMessage({
                            message: "提交成功",
                            type: "success"
                        });
                        router.push("/main/reportManage");
                        store.treeSelectNode = {};
                    }
                })
                .catch((err) => (loading.value = false));
            break;
        case 2:
            formConfig.value = examineConfrimConfig;
            popFormData.value = examinePopFormData;
            rules = examineConfrimRules;
            examineType = 0;
            isShowExaminePopup.value = true;
            break;
        case 3:
            break;
        case 4:
            loading.value = true;
            const repairDetailClone = cloneDeep(repairDetail.value);
            repairDetailClone.repairDetails.forEach((item) => {
                item.disposeOperaterName = mStore.userInfo.showName;
                item.disposeOperaterId = mStore.userInfo.userId;
                item.images = item.images.map((item) => item.id).join(",");
                item.disposeImages = item.disposeImages.map((item) => item.id).join(",");
                item.repairFeedbackInfos.forEach((item) => {
                    item.disposalMethod = item.handle;
                    delete item.checks;
                    delete item.handles;
                });
            });
            setHandler(repairDetailClone)
                .then((res) => {
                    loading.value = false;
                    if (res.code === 200) {
                        ElMessage({
                            message: "处理成功",
                            type: "success"
                        });
                        router.push("/main/reportManage");
                    }
                })
                .catch(() => (loading.value = true));
            break;
        case 5:
            if (!distributionRef.value.chooseData.length) {
                ElMessage({
                    message: "请分配人员和对象",
                    type: "error"
                });
                return;
            }
            loading.value = true;
            const tree = distributionRef.value.chooseData;
            const userStructure = tree.map((item) => ({
                userName: item.name,
                userId: item.id,
                structureIds: [...item.childs.map((item) => item.id)]
            }));
            setAssign({
                userStructure,
                orderId: repairDetail.value.jobOrderId,
                orderCode: repairDetail.value.jobOrderNo,
                equipmentId: repairDetail.value.deviceId,
                operator: mStore.userInfo.userId,
                equipmentName: repairDetail.value.deviceName,
                state: 4
            })
                .then((res) => {
                    loading.value = false;
                    if (res.code === 200) {
                        ElMessage({
                            message: "派发成功",
                            type: "success"
                        });
                        router.push("/main/reportManage");
                    }
                })
                .catch(() => (loading.value = false));
            break;
        case 6:
            loading.value = true;
            acceptRepair({
                status: examineType,
                id: repairDetail.value.jobOrderId
            })
                .then((res) => {
                    loading.value = false;
                    isShowExaminePopup.value = false;
                    if (res.code === 200) {
                        ElMessage({
                            message: "验收成功",
                            type: "success"
                        });
                        router.push("/main/reportManage");
                    }
                })
                .catch(() => (loading.value = false));
            break;
    }
};
const rightBtnClick = () => {
    switch (store.stateOperation) {
        case 1:
            router.push("/main/reportManage");
            store.treeSelectNode = {};
            break;
        case 2:
            examineTitle.value = "审核";
            examineRejectConfig[0].labelName = "不通过理由";
            examineRejectConfig[0].placeholder = "请输入需整改理由";
            formConfig.value = examineRejectConfig;
            popFormData.value = rejectPopFormData;
            rules = rejectRules;
            examineType = 1;
            isShowExaminePopup.value = true;
            break;
        case 3:
            break;
        case 4:
            router.push("/main/reportManage");
            break;
        case 5:
            router.push("/main/reportManage");
            break;
        case 6:
            examineTitle.value = "结果审核";
            examineRejectConfig[0].labelName = "需整改理由";
            examineRejectConfig[0].placeholder = "请输入需整改理由";
            formConfig.value = examineRejectConfig;
            popFormData.value = rejectPopFormData;
            examineType = 1;
            isShowExaminePopup.value = true;
    }
};
const popupClose = () => {
    isShowExaminePopup.value = false;
    rejectPopFormData.remark = "";
};
const popupConfrim = (examineType) => {
    wFormRef.value.ruleFormRef.validate((isValid) => {
        if (isValid) {
            loading.value = true;
            const api = store.stateOperation === 2 ? checkRepair : acceptRepair;
            api({
                grade: examinePopFormData.grade,
                deptId: examinePopFormData.department,
                content: rejectPopFormData.remark,
                status: examineType,
                id: repairDetail.value.jobOrderId
            })
                .then((res) => {
                    loading.value = false;
                    if (res.code === 200) {
                        isShowExaminePopup.value = false;
                        router.push("/main/reportManage");
                        ElMessage({
                            message: store.stateOperation === 2 ? "审核成功" : "验收成功",
                            type: "success"
                        });
                    }
                })
                .catch(() => (loading.value = false));
        }
    });
};

const isShowProcessPopup = ref(false);
const processClick = () => {
    isShowProcessPopup.value = true;
};
const peopleTree = ref([]);
const responsible = ref([]);
const distributionRef = ref(null);
const api2 = [{ api: getDpt, index: 0 }, , { api: getReportDist, index: 1, name: "Repair_Order_Level" }];
const btnText = ref({ left: "提交", right: "取消" });
getReapir();
function getReapir() {
    loading.value = true;
    if (!mStore.tableData.id) {
        store.stateOperation = 1;
        repairDetail.value = mStore.tableData;
        getApiData(api2, examineConfrimConfig);
        store.getDeviceTree({ id: Number(mStore.tableData.areaNameId), strategyId: mStore.tableData.strategyId, structureType: 1 }, () => {
            nextTick(() => {
                orderTreeRef.value.treeCpnRef.treeRef.setCurrentKey(store.treeData[0]?.childList[0]?.id);
            });
            handlerNode({ level: 2, data: store.treeData[0]?.childList[0] });
        });
        btnText.value = { left: "提交", right: "取消" };
        loading.value = false;
        return;
    }
    getReapirDetail(route.query.orderCode || mStore.tableData.id)
        .then((res) => {
            loading.value = false;
            repairDetail.value = res;
            const state = Number(repairDetail.value.status);
            switch (state) {
                case 1:
                    getApiData(api2, examineConfrimConfig);
                    store.stateOperation = 2;
                    btnText.value = { left: "通过", right: "不通过" };
                    break;
                case 2:
                    store.stateOperation = 3;
                    break;
                case 3:
                    store.stateOperation = 5;
                    btnText.value = { left: "派工", right: "取消" };
                    break;
                case 4:
                    store.stateOperation = 4;
                    break;
                case 5:
                    store.stateOperation = 6;
                    btnText.value = { left: "通过", right: "需整改" };
                    break;
                case 6:
                    store.stateOperation = 3;
                    break;
                case 7:
                    store.stateOperation = 3;
                    break;
            }
            nextTick(() => {
                if (store.stateOperation !== 5) {
                    repairDetail.value?.repairDetails.forEach((item) => {
                        if (item.images) {
                            item.images = item.images.split(",")?.map((item) => ({
                                id: "",
                                url: BASE_URL + item
                            }));
                        } else {
                            item.images = [];
                        }
                        if (item.disposeImages) {
                            item.disposeImages = item.disposeImages.split(",")?.map((item) => ({
                                id: "",
                                url: BASE_URL + item
                            }));
                        } else {
                            item.disposeImages = [];
                        }
                        item.repairFeedbackInfos.forEach((item) => {
                            item.handles = item.disposalMethods?.map((item) => ({ label: item, value: item }));
                            item.checks = item.inspectionResults?.map((item) => ({ label: item, value: item }));
                        });
                    });
                    if (feedbackRef.value?.tableRef?.tableData) feedbackRef.value.tableRef.tableData = repairDetail.value?.repairDetails[0]?.repairFeedbackInfos;
                    associationPolicyRef.value.tableRef.tableData = repairDetail.value?.repairDetails[0]?.repairFeedbackInfos;
                    detail.value = repairDetail.value?.repairDetails[0];
                }
            });
            if (store.stateOperation === 5) {
                const tree = [];
                for (let i = 0; i < res.repairDetails.length; i++) {
                    const findParent = tree.find((item) => item.id === res.repairDetails[i].parentStructureId);
                    const detailMap = {
                        code: res.repairDetails[i].code,
                        images: res.repairDetails[i].images,
                        parentId: res.repairDetails[i].parentStructureId,
                        remark: res.repairDetails[i].remark,
                        repairFeedbackInfos: res.repairDetails[i].repairFeedbackInfos,
                        id: res.repairDetails[i].structureId,
                        name: res.repairDetails[i].structureName
                    };
                    if (findParent) {
                        findParent.childs.push(detailMap);
                    } else {
                        tree.push({ name: res.repairDetails[i].parentStructureName, id: res.repairDetails[i].parentStructureId, childs: [detailMap] });
                    }
                }
                responsible.value = tree;
            }
        })
        .catch(() => (loading.value = false));
}
const handlerNode = async (node) => {
    if (!node.data) return;
    if (node.level !== 1) {
        associationPolicyRef.value.tableRef.tableData = [];
        store.treeSelectNode = node.data;
        if (node.data.tableData?.length) {
            associationPolicyRef.value.tableRef.tableData = node.data.tableData;
            node.data.hot.forEach((item) => {
                nextTick(() => {
                    associationPolicyRef.value.tableRef.tableRef.toggleRowSelection(item, true);
                });
            });
        } else {
            const res = await getStructureTreeList({
                structureId: node.data.id,
                depth: "1"
            });
            if (res.code === 200) {
                res.data.forEach((item) => {
                    item.check = "";
                    item.handle = "";
                    item.disable = false;
                });
                associationPolicyRef.value.tableRef.tableData = res.data;
                node.data.tableData = res.data;
            }
        }
        store.treeSelectNode.tableData.forEach((item) => {
            item.handles = item.disposalMethodText?.split(";").map((item) => ({ label: item, value: item }));
            item.checks = item.inspectionResultText?.split(";").map((item) => ({ label: item, value: item }));
        });
    }
};
function getApiData(apiArray, config) {
    apiArray.forEach((item) => {
        item.api({ parentCode: item.name }).then((res) => {
            if (res.code === 200) {
                config[item.index].options = res.data.map((item) => ({ label: item.name, value: item.value }));
            }
        });
    });
}
</script>

<style lang="less" scoped>
.order-detail {
    font-size: 16px;
    .order-item {
        display: grid;
        grid-template-columns: repeat(6, minmax(180px, 1fr));
        grid-template-rows: repeat(auto, 54px);
        grid-gap: 10px;
        margin-top: 16px;
        .item {
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 54px;
            background: #f8fafa;
            color: #595959;
            cursor: pointer;
            .hot {
                margin-right: 8px;
                width: 8px;
                height: 8px;
                border-radius: 50%;
                background: #ffc53f;
            }
        }
        .item-active {
            background: #fff;
            color: #1b3646;
            font-weight: 600;
            .hot {
                background: #a0d911;
            }
        }
    }
    .order-main {
        display: flex;
        margin-top: 16px;
        .left {
            box-sizing: border-box;
            margin-right: 16px;
            padding: 16px;
            min-width: 284px;
            height: 726px;
            background-color: #fff;
            overflow: auto;
        }
        .right {
            box-sizing: border-box;
            flex: 1;
            padding: 16px;
            height: 726px;
            background-color: #fff;
            overflow: auto;
        }
    }
    .feedback {
        margin-top: 16px;
        padding: 16px;
        background-color: #fff;
    }
    .examine {
        margin-top: 16px;
        padding: 16px;
        background-color: #fff;
        .examine-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            span {
                color: #1b3646;
                &:first-child {
                    font-weight: 600;
                }
                &:last-child {
                    font-size: 14px;
                }
            }
        }
        .examine-article {
            margin-top: 16px;
            font-size: 14px;
            color: #595959;
        }
    }
    .btns {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 16px;
        height: 64px;
        background-color: #fff;
        .confrim {
            width: 80px;
            height: 32px;
        }
    }
    .notice-one {
        margin-top: 10px;
        margin-bottom: 16px;
        font-size: 14px;
        color: #1b3646;
    }

    .process {
        ::v-deep(.btns) {
            justify-content: flex-end;
        }
    }
}
</style>
